import { ref, watch } from 'vue'
import {defineStore} from 'pinia'
import { getLoginUserUsingGet } from '@/api/userController.ts'
import accessEnum from '@/access/accessEnum.ts'
import ACCESS_ENUM from '@/access/accessEnum.ts'

/**
 * 存储登录用户信息的状态
 */
export const useLoginUserStore = defineStore('loginUser', () => {
  const loginUser = ref<API.LoginUserVO>({
    userName: '未登录',
    userRole: accessEnum.NOT_LOGIN
  })

  async function fetchLoginUser() {
    const res = await getLoginUserUsingGet();
    if (res.data.code === 200 && res.data.data) {
      loginUser.value = res.data.data;
    }
    // 测试用户登录，3 秒后自动登录
    // setTimeout(() => {
    //   loginUser.value = { userName: '测试用户', id: 1 }
    // }, 3000)
  }

  /**
   * 设置登录用户
   * @param newLoginUser
   */
  function setLoginUser(newLoginUser: any) {
    loginUser.value = newLoginUser
  }

  const saveState = () => {
    localStorage.setItem('loginUser', JSON.stringify(loginUser.value));
  };

  const clearState = () => {
    loginUser.value = {
      userAccount: "未登录",
      userRole: ACCESS_ENUM.NOT_LOGIN,
    };
    localStorage.removeItem('loginUser');
  };

  // 监听状态变化并保存
  watch(
    () => loginUser.value,
    () => saveState(),
    { deep: true }
  );

  // 返回
  return { loginUser, fetchLoginUser, setLoginUser, clearState }
})
